import http from './http'
import { getRouteQuery } from '@/utils'

// 微信获取表单信息
export const useSign = (values: any) => http.post('h5/wechat/get_jsapi_ticket/', { ...values }).catch(() => undefined)

// 获取openid
export const useOpenID = (code: string) => http.post('/h5/wechat/open_id/', { code }).then((res: LooseObject) => {
  if (res.open_id) localStorage.setItem('x_wechat_open_id', res.open_id)
  return Promise.resolve(res.open_id)
})

export const useWxLogin = () => {
  const Query: any = getRouteQuery()
  if (Reflect.has(Query, 'code')) useOpenID(Query.code)
  else if (!localStorage.getItem('x_wechat_open_id')) {
    const redirect_uri = encodeURIComponent(window.location.href)
    const state = new Date().getTime()
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${import.meta.env.XMOV_APP_WX_APPID
      }&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`
  }
}

// 用户登录
export const login = (params: LooseObject) => http.post('/h5/bs/login/', params)
